import xqykjzz  from './cwbbData.js'
import { asyncSetInterval,fixZeroInfo } from "../../lib/zeroReportUtils.js";
/* eslint-disable */
const autoInputAccount = ({
  nationalTaxNo,
  nationalTaxPass,
  nationalTaxUser,
}) => {
  document.querySelector("#dl").click();
  document.querySelector("#li_yhm").click();
  document.querySelector("#userName").value = nationalTaxUser;
  document.querySelector("#passWord").value = nationalTaxPass;
};

const getDbList = async () => {
  // console.log(currentZeroInfo);
  let trs = document.querySelectorAll("#wddb > table > tbody tr");
  return trs ? Array.from(trs) : [];
};

const zzsfpzhfwpdOption = async (currentZeroInfo) => {
  asyncSetInterval(() => {
    if ($("#ssq").length) {
      return $("#ssq").text();
    }
  })
    .then((res) => {
      let year = parseInt(res.split("年")[0]);
      let month = parseInt(res.split("年")[1]);
      if (
        year === currentZeroInfo.year &&
        month === currentZeroInfo.endPeriod
      ) {
        window.loadUrl("dkgx_fpdk.ac95712e.html");
        return asyncSetInterval(() => {
          if ($("#search").length) {
            $("#search").click();
            return true;
          }
        }, 1000);
      }
    })
    .then(() => {
      return asyncSetInterval(() => {
        if ($("#popup_ok").length) {
          $("#popup_ok").click();
          return true;
        }
      });
    })
    .then((rs) => {
      window.loadUrl("dkgx_dktj.da4829eb.html");
      return asyncSetInterval(() => {
        if ($("#sqtj_button").length) {
          $("#sqtj_button").click();
          return true;
        }
      }, 1000);
    })
    .then((rs) => {
      return asyncSetInterval(() => {
        if ($("#popup_ok").length) {
          $("#popup_ok").click();
          return true;
        }
      }, 1000);
    })
    .then((rs) => {
      // $('#qrtj_button')
      return asyncSetInterval(() => {
        if ($("#qrtj_button").length) {
          $("#qrtj_button").click();
          return true;
        }
      }, 1000);
    })
    .then((rs) => {
      return asyncSetInterval(() => {
        if ($("#popup_ok").length) {
          $("#popup_ok").click();
          return true;
        }
      }, 1000);
    })
    .then((rs) => {
      // #password 密码输入
      
    })
};

const zzsYbTableOption = async () => {
  return asyncSetInterval(() => {
    let iframe = $("#myTabIframe");
    if (
      iframe.length &&
      iframe.contents().find("#formId") &&
      $("#css_spin_div > div").length == 0
    ) {
      document.getElementById("myTabIframe").contentWindow.Save();
      return true;
    }
  }, 1000)
    .then(() => {
      return asyncSetInterval(() => {
        if (
          $("#myTabIframe")
            .contents()
            .find(
              "div.panel.window.messager-window > div.dialog-button.messager-button > a"
            ).length
        ) {
          let alist = $("#myTabIframe")
            .contents()
            .find("div.panel.window.messager-window");
          let currenta = Array.from(alist).find(
            (item) => item.style.display === "block"
          );
          if (currenta) {
            $(currenta).find("a")[0].click();
            window.doXdsNextPage("01", "1", "", "");
            return true;
          }
        }
      }, 1000);
    })
    .then((rs) => {
      if (rs) {
        return asyncSetInterval(() => {
          return true;
        }, 1000);
      }
    });
};

const submitBtns = async () => {
  return asyncSetInterval(() => {
    let iframe = $("#myTabIframe");
    if (
      iframe.length &&
      iframe.contents().find("#divMaintable") &&
      iframe
        .contents()
        .find(
          "#divMaintable > div.bd.mysmtable.sideMenu > ul > table > tbody:nth-child(1) > tr > td > a:nth-child(3)"
        ).length
    ) {
      iframe
        .contents()
        .find(
          "#divMaintable > div.bd.mysmtable.sideMenu > ul > table > tbody:nth-child(1) > tr > td > a:nth-child(3)"
        )[0]
        .click();
      return true;
    }
  }, 1000)
    .then((rs) => {
      return asyncSetInterval(() => {
        if (
          $("#myTabIframe")
            .contents()
            .find(
              "div.panel.window.messager-window > div.dialog-button.messager-button > a"
            ).length
        ) {
          let alist = $("#myTabIframe")
            .contents()
            .find("div.panel.window.messager-window");
          let currenta = Array.from(alist).find(
            (item) => item.style.display === "block"
          );
          if (currenta) {
            $(currenta).find("a")[0].click();
            return true;
          }
        }
      }, 1000);
    })
    .then((rs) => {
      let iframe = $("#myTabIframe");
      if (
        iframe.length &&
        iframe.contents().find("#divMaintable") &&
        iframe
          .contents()
          .find(
            "#divMaintable > div.bd.mysmtable.sideMenu > ul > table > tbody:nth-child(3) > tr > td > a:nth-child(3)"
          ).length
      ) {
        iframe
          .contents()
          .find(
            "#divMaintable > div.bd.mysmtable.sideMenu > ul > table > tbody:nth-child(3) > tr > td > a:nth-child(3)"
          )[0]
          .click();
        return true;
      }
    })
    .then((rs) => {
      return asyncSetInterval(() => {
        if (
          $("#myTabIframe")
            .contents()
            .find(
              "div.panel.window.messager-window > div.dialog-button.messager-button > a"
            ).length
        ) {
          let alist = $("#myTabIframe")
            .contents()
            .find("div.panel.window.messager-window");
          let currenta = Array.from(alist).find(
            (item) => item.style.display === "block"
          );
          if (currenta) {
            $(currenta).find("a")[0].click();
            window.doXdsNextPage("01", "1", "", "");
            return true;
          }
        }
      }, 1000);
    });
};

const getResult = async () => {
  return asyncSetInterval(() => {
    let iframe = $("#myTabIframe");
    let td = iframe
      .contents()
      .find(
        "body > div.content_all > div > div.content > div.bd.Myrenwutab > table > tbody > tr:nth-child(1) td:nth-child(5)"
      );
    if (iframe.length && iframe.contents().find("#divMaintable") && td.length) {
      if (td.text() === "未申报") window.location.reload();
      else {
        let trs = iframe
          .contents()
          .find(
            "body > div.content_all > div > div.content > div.bd.Myrenwutab > table > tbody > tr"
          );
        let list = [];
        Array.from(trs).forEach((item) => {
          let accountBookArr = $(item)
            .find("td:nth-child(3)")
            .text()
            .split("-");
          let start = $(item).find("td:nth-child(2)").text().split("-");
          let declareCycle = parseInt(accountBookArr[1]) - parseInt(start[1]);
          let declareName = $(item).find("td:nth-child(1)").text();
          let obj = {
            declareName,
            accountBook: accountBookArr[0] + "-" + accountBookArr[1],
            // eslint-disable-next-line no-nested-ternary
            declareCycle:
              declareCycle === 2
                ? "season"
                : declareCycle === 11
                ? "year"
                : "month",
            isSuccess: $(item).find("td:nth-child(5)").text() === "申报成功",
          };
          if (!list.find((items) => items.declareName === declareName)) {
            list.push(obj);
          }
        });
        window.postMessage(
          {
            event: "baoBiaoDetailBack",
            data: {
              step: 2,
              isclose: true,
              type: "zzsYb",
              list,
            },
          },
          "*"
        );
      }
      return true;
    }
  }, 1000);
};

const handleCwbbZcfzb = async ({ cwbbInfo, customerType }) => {
  return asyncSetInterval(()=>{
    let myTabIframe = $('#myTabIframe').contents();
    let zcfzb = cwbbInfo.zcfzb;
    let systemData = false;
    let shuijuData = false;
    let zcfzbDefault = customerType.includes("小企业会计准则")
      ? xqykjzz.balance
      : "";
    let result = Object.keys(zcfzbDefault).map((key) => {
      let col = zcfzbDefault[key];
      let colValue = zcfzb[col];
      let value =
        key.includes("l2") || key.includes("l5") ? colValue.qmye : colValue.ncye;
      if (parseFloat(value)) systemData = true;
      if (parseFloat(myTabIframe.find(`#${key}`).val())) shuijuData = true;
      // myTabIframe.find(`#${key}`).val(1 || 0.0);
      return {
        key,
        value,
      };
    });
    if (systemData) {
      result.forEach(({ key, value }) => {
        myTabIframe.find(`#${key}`).val(value || 0.0);
      });
    } else if (!shuijuData && !systemData) {
      let arr = ["h9l2", "h9l3", "h29l5", "h29l6"];
      arr.forEach((item) => {
        myTabIframe.find(`#${key}`).val(0.01);
      });
    }
    $('#xds_btn_next').click();
    return true;
  },1000)
}

const handleCwbbLrb = async ({ cwbbInfo, customerType }) => {
  return asyncSetInterval(()=>{
    let myTabIframe = $('#myTabIframe').contents();
    let lrb = cwbbInfo.lrb;
    let lrbDefault = customerType.includes("小企业会计准则")
      ? xqykjzz.profit
      : "";
    let result = Object.keys(lrbDefault).map((key) => {
      let col = lrbDefault[key];
      let colValue = lrb[col];
      let value =
        key.includes("l2") ? colValue.bqje : colValue.bnljje;
      // myTabIframe.find(`#${key}`).val(1 || 0.0);
      return {
        key,
        value,
      };
    });
    result.forEach(({ key, value }) => {
      myTabIframe.find(`#${key}`).val(value || 0.0);
    });
    $('#xds_btn_next').click();
    return true;
  },1000)
}

const handleCwbbXjllb = async ({ cwbbInfo, customerType }) => {
  return asyncSetInterval(()=>{
    let myTabIframe = $('#myTabIframe').contents();
    let xjllb = cwbbInfo.xjllb;
    let xjllbDefault = customerType.includes("小企业会计准则")
      ? xqykjzz.cash
      : "";
    let result = Object.keys(xjllbDefault).map((key) => {
      let col = xjllbDefault[key];
      let colValue = xjllb[col];
      let value =
        key.includes("l2") ? colValue.bqje : colValue.bnljje;
      // myTabIframe.find(`#${key}`).val(1 || 0.0);
      return {
        key,
        value,
      };
    });
    result.forEach(({ key, value }) => {
      myTabIframe.find(`#${key}`).val(value || 0.0);
    });
    $('#xds_btn_next').click();
    return true;
  },1000)
}

const handleCwbb = async (info) => {
  // let tables = $('#myTabzl .infoList > li').length;
  await handleCwbbZcfzb(info);
  await handleCwbbLrb(info);
  await handleCwbbXjllb(info);
}

const handleZzs = async () => {
  console.log('handleZzs')
  asyncSetInterval(async ()=>{
    let tables = $('#myTabzl .infoList > li').length
    for(let i = 0; i < tables; i++) {
      await nextBtnClick();
    }
    return true;
  },1000)
}

const handleSds = async (info) => {
  console.log('info',info)
  asyncSetInterval(async ()=>{
    let tables = $('#myTabzl .infoList > li').length
    let myTabIframe = $('#myTabIframe').contents();
    let pop = myTabIframe.find('#xxfyyh');
    let msgBOX = myTabIframe.find('.messager-window');
    let quarter = info.endPeriod / 3;
    if (pop.length) {
      myTabIframe.find('.panel-tool-close')[0].click()
    }
    if (msgBOX.length) {
      msgBOX.find('.panel-tool-close')[0].click();
    }
    myTabIframe.find(`#qccyrs${quarter}`).val(1);
    myTabIframe.find(`#qmcyrs${quarter}`).val(1);
    myTabIframe.find(`#qczcze${quarter}`).val(parseFloat(info.quarterSum / 10000) || 0.01);
    myTabIframe.find(`#qczcze${quarter}`).blur();
    myTabIframe.find(`#qmzcze${quarter}`).val(parseFloat(info.endSum / 10000) || 0.01);
    myTabIframe.find(`#qmzcze${quarter}`).blur();
    myTabIframe.find('#BDA0611033_A > div > div > div.Mytab > table:nth-child(6) > tbody > tr:nth-child(2) > td:nth-child(2) > input[type=radio]:nth-child(2)').click();
    myTabIframe.find('#BDA0611033_A > div > div > div.Mytab > table:nth-child(6) > tbody > tr:nth-child(2) > td:nth-child(4) > input[type=radio]:nth-child(2)').click();
    myTabIframe.find('#BDA0611033_A > div > div > div.Mytab > table:nth-child(6) > tbody > tr:nth-child(3) > td:nth-child(2) > input[type=radio]:nth-child(2)').click();
    tables--;
    await asyncSetInterval(()=>{
      $('#xds_btn_next').click();
      return true;
    },1000)
    return tables;
  },1000).then(async (tables)=>{
    for(let i = 0; i < tables; i++){
      await nextBtnClick();
    }
  })
}

const handleFjs = async () => {
  asyncSetInterval(async ()=>{
    let myTabIframe = $('#myTabIframe').contents();
    let msgBox = myTabIframe.find('.messager-window');
    if (msgBox.length) {
      msgBox.find('.messager-button > a')[0].click();
    }
    await nextBtnClick();
    return true;
  },1000)
}

const nextBtnClick = async () => {
  return asyncSetInterval(()=>{
    let nextBtn = $('#xds_btn_next');
    if (nextBtn.length) {
      nextBtn.click()
    }
    return true;
  },1000)
}

const submitReportItem = async (num) => {
  return asyncSetInterval(async ()=>{
    let myTabIframe = $('#myTabIframe').contents();
    let reportList = myTabIframe.find('#divMaintable > div.bd.mysmtable.sideMenu > ul > table > tbody');
    reportList = Array.from(reportList).filter(item => !($(item).hasClass("dd")))
    let cwbbIndex = reportList.findIndex(item => $(item).find('tr > td').text().includes('财务报表'));
    let cwbb = reportList.splice(cwbbIndex,1);
    reportList.unshift(...cwbb);
  
    let reportBtn = $(reportList[num]).find('tr > td > a:eq(0)');
    if (reportBtn.text().includes('正式提交申报')) {
      reportBtn.click();
      await asyncSetInterval(()=>{
        let msgBox = myTabIframe.find('body > div:nth-child(14)');
        let errBox = myTabIframe.find('body > div.panel.window.messager-window');
        console.log('msgBox',msgBox[0])
        console.log('errBox',errBox[0])
        console.log('errBox-style',errBox.css('display'))
        console.log('errBox-txt',errBox.text())
        let display = errBox.css('display');
        if (errBox.length && display != 'none') {
          window.location.reload();
        }else {
          if (msgBox.length) {
            msgBox.find('.messager-button > a')[0].click();
          }
        }
        return true;
      },2000)
    }
    return true;
  },1000)
}


const submitReport = async () => {
  asyncSetInterval(async ()=>{
    let myTabIframe = $('#myTabIframe').contents();
    let reportList = myTabIframe.find('#divMaintable > div.bd.mysmtable.sideMenu > ul > table > tbody');
    reportList = Array.from(reportList).filter(item => !($(item).hasClass("dd")))
    console.log('reportList',reportList)
    for(let i = 0; i < reportList.length; i++) {
      await submitReportItem(i);
    }
    await nextBtnClick();
    return true;
  },1000)
}

const syncReportStatus = async (info) => {
  asyncSetInterval(()=>{
    console.log('info',info)
    let trList = $('#myTabIframe').contents().find('.Myrenwutab > table > tbody > tr');
    let recordList = Array.from(trList).map(item => {
      let declareName = $(item).find('td:eq(0)').text();
      let isSuccess = $(item).find('td:eq(4)').text() === "申报成功" ? true : false;
      let startDate = $(item).find('td:eq(1)').text().split('-');
      let endDate = $(item).find('td:eq(2)').text().split('-');
      let month = endDate[1] - startDate[1];
      let declareCycle = "month";
      declareName.includes('年') ? declareCycle = "year" : '';
      declareName.includes('季') ? declareCycle = "season" : '';
      return {
        declareName,
        accountBook: `${endDate[0]}-${endDate[1]}`,
        declareCycle: month === 11 ? 'year' : month === 2 ? 'season' : 'month',
        isSuccess,
      };
    })
    let obj = {}
    let UniqueRecordList = recordList.reduce((acc,cur) => {
      obj[cur.declareName] ? '' : obj[cur.declareName] = true && acc.push(cur);
      return acc;
    },[])
    console.log('recordList',UniqueRecordList)
    fixZeroInfo({recordList:UniqueRecordList});
    setTimeout(() => {
      window.location.href = 'https://etax.hubei.chinatax.gov.cn/portal/home.c';
    }, 1000);
    return true;
  },1000)
}

const zzsfpzhfwSB = async (currentZeroInfo) => {
  let reportList = {};
  let search = window.location.search
  .slice(1)
  .split("&")
  .reduce((c, item) => {
    let arr = item.split("=");
    c[arr[0]] = arr[1];
    return c;
  }, {});
  let {menu,con} = search;
  console.log('search:',menu,con)
  asyncSetInterval(()=>{
    let lis = Array.from($('.picList > li'));
    for(let i = 0; i < lis.length; i++){
      let subject = $(lis[i]).find('div > p').text();
      if (subject.includes("开始") || subject.includes("结束")){
        continue;
      }
      reportList[i] = subject;
    }

    console.log('reportList:', reportList);

    if(menu || con === '0') {
      nextBtnClick();
    }
    if (con === '1' && reportList[con].includes('财务报表')) {
      handleCwbb(currentZeroInfo);
    }
    if (con === '2' && reportList[con].includes('增值税')) {
      handleZzs();
    }
    if (con === '3' && reportList[con].includes('所得税')) {
      handleSds(currentZeroInfo);
    }
    if (con === '4' && reportList[con].includes('《附税申报》')) {
      handleFjs();
    }
    if (con === '5' && reportList[con].includes('提交申报')) {
      submitReport();
    }
    if (con === '6' && reportList[con].includes('扣款信息')) {
      nextBtnClick();
    }
    if (con === '7' && reportList[con].includes('申报扣款查询')) {
      syncReportStatus(currentZeroInfo)
    }
    return true;
  },1000)
  // console.log(currentZeroInfo);
  // setTimeout(async () => {
  //   let search = window.location.search
  //     .slice(1)
  //     .split("&")
  //     .reduce((c, item) => {
  //       let arr = item.split("=");
  //       c[arr[0]] = arr[1];
  //       return c;
  //     }, {});
  //   if (parseInt(search.con) === 1) {
  //     let lis = $("#myTabzl > div.bd > div > ul > li").length;
  //     for (let i = 0; i < lis; i++) {
  //       // eslint-disable-next-line no-await-in-loop
  //       await zzsYbTableOption();
  //     }
  //   } else if (parseInt(search.con) === 2) {
  //     window.doXdsNextPage("01", "1", "", "");
  //   } else if (parseInt(search.con) === 3) {
  //     submitBtns();
  //   } else if (parseInt(search.con) === 5) {
  //     getResult();
  //   } else {
  //     window.doXdsNextPage("01", "1", "", "");
  //   }
  // }, 1000);
};

const asyncTable = async (data) => {
  console.log(data);
};

const getTableDetail = (name, endPeriod) => {
  let ifm = $("#ifm");
  let trs = ifm
    .contents()
    .find(
      "body > div.content_all > div > div.content > div.bd.Myrenwutab > table > tbody > tr"
    );
  return Array.from(trs).find(
    (item) =>
      $(item).find("td:nth-child(1)").text() === name &&
      $(item).find("td:nth-child(3)").text().includes(endPeriod)
  );
};

const sbbdy = async (info) => {
  let {year,endPeriod} = info;
  let ifm = $("#ifm");
  let queryBtn = ifm.contents().find('#myForm > table > tbody > tr > td:nth-child(2) > div');
  if (queryBtn.length) {
    queryBtn.click();
  }
  let endTime = `${year}-${endPeriod < 10 ? "0" + endPeriod : endPeriod}`;

  asyncSetInterval(async ()=>{
    if (ifm.length) {
      let zzsybnsr = getTableDetail(
        "《增值税纳税申报表（一般纳税人适用）》",
        endTime
      );
      let fjs = getTableDetail(
        "《城建税、教育费附加、地方教育附加税（费）申报表》",
        endTime
      );
      let zzsXgm =  getTableDetail(
        "《增值税纳税申报表（小规模纳税人适用）》",
        endTime
      );
      let qs = getTableDetail(
        "《A200000中华人民共和国企业所得税月（季）度预缴纳税申报表（A类，2018年版）》",
        endTime
      );

      let tableArr = [zzsybnsr,fjs,zzsXgm,qs].filter(Boolean);
      console.log('tableArr',tableArr);
      for(let i = 0; i < tableArr.length; i++) {
        await asyncSetInterval(()=>{
          $(tableArr[i]).find("td:nth-child(5) span").click();
          return true;
        },2000)
      }
      setTimeout(() => {
        window.postMessage({
          event: 'zeroReportBack',
          data: { ...info }
        }, '*');
      }, 8000);
    }
    return true;
  },500)
};

function isdisplay(id) {
  let element = document.getElementById(id);
  return element && element.style.display !== "none";
}

// 处理html片段
function dealHtml(id) {
  var a_html = document.getElementById(id).outerHTML;
  var re = /([a-zA-Z_\u4e00-\u9fa5-\u4e00-\u9fa5]+\=)([#a-zA-Z0-9_\u4e00-\u9fa5-\u4e00-\u9fa5]+)/gi;
  a_html = a_html.replace(re, '$1"$2"');
  // 每个页面重组的时候因为css样式的问题，需要回车换行，一般两个中间放两个</br>
  a_html = a_html.replace(/\"/g, "'");
  a_html = a_html.replace(/<br>/g, "<br></br>");
  a_html = a_html.replace(/<BR>/g, "<br></br>");
  var html = a_html + "<br></br>";
  html = lowtag(html);
  return html;
}

// 保存明细表
const saveTableDetail = (tableContent) => {
  window.postMessage(
    {
      event: "asyncTableDetail",
      data: tableContent,
    },
    "*"
  );
};

const getTableUrl = async (temp) => {
  return new Promise((resolve, reject) => {
    $.ajax({
      type: "POST",
      url:
        GLOB_CONTEXT_PATH + "/cssnj/ajax.action?tld=HtmlToPdfService_htmlToPdf",
      data: JSON.stringify(temp),
      dataType: "html",
      async: true,
      success: function (data) {
        var jsonData = JSON.parse(data);
        if (jsonData.recode == "1") {
          let url =
            "https://etax.hubei.chinatax.gov.cn" +
            GLOB_CONTEXT_PATH +
            "/printFileSrv/downloadPdf.action?path=" +
            jsonData.path;
          resolve(url);
        } else {
          console.log("导出报错:" + data.errorMsg);
        }
      },
      error: function (responseText, textStatus, XMLHttpRequest) {
        console.log(textStatus);
      },
    });
  });
};
const zzsSaveTableDetail = (id, html, declareType) => {
  declareType = declareType || "《增值税纳税申报表（一般纳税人适用）》"
  let titleHtml = document.querySelector(`#${id} > div > div.Mytab_tit > h2`) || document.querySelector(`#${id} > div > div.Mytab_tit`);
  let tableContent = {
    declareType,
    title: titleHtml.innerText,
    html,
    css: `.all .Mytab_tit { text-align: center; font-weight: 25px; line-height: 40px;font-weight: bold;}
		.all ul { list-style: none;}
		.all table { border-collapse: collapse;}
		.all table td { border: 1px solid #ddd;}`
  };
  saveTableDetail(tableContent);
};
async function htmToPdf1(id) {
  return new Promise((resolve) => {
    if (!isdisplay(id)) {
      if(id === 'zzsybnsrzb') {
        resolve(false);
      } else {
        resolve(true);
      }
    } else {
      let html = dealHtml(id);
      zzsSaveTableDetail(id, html);
      setTimeout(() => {
        resolve(true);
      }, 200);
    }
  })
}
const zzsybnsrPrint = async (currentZeroInfo) => {
  let ids = ["zzsybnsrfb1", 'zzsybnsrfb3', 'zzsybnsrmx', 'zzsybnsrfb2', 'zzsybnsrfb5', 'zzsybnsrfb4', 'zzsybnsrzb'], result = [];
  for(let i = 0; i< ids.length; i++) {
    let idItem = ids[i];
    let rre = await htmToPdf1(idItem);
    result.push(rre);
  }
  if(result.find(item => !item)) {
    setTimeout(() => {
      window.location.reload();
    }, 2000);
  }
};

const fsjPrint = async (currentZeroInfo) => {
  let id = 'fssbdiv';
  let html = dealHtml(id);
  console.log('html',html);
  zzsSaveTableDetail(id, html, '《附税申报》');
  setTimeout(() => {
    window.postMessage({
      event: 'closeTabs',
      data: ''
    }, '*');
  }, 1000);
}

const qsPrint = async (currentZeroInfo) => {
  console.log('qs');
  let tables = Array.from($('#qysdsA_1 > .content'));
  let declareType = "《企业所得税月（季）度预缴纳税申报表（A类，2018年版）》";
  for(let i = 0; i < tables.length; i++) {
    await asyncSetInterval(()=>{
      let titleHtml = $(tables[i]).find('.Mytab_tit').text();
      let html = $(tables[i]).prop('outerHTML');
      let tableContent = {
        declareType,
        title: titleHtml,
        html,
        css: `.content{position:relative;border:1px solid #f2f2f2;background-color:#fff;padding:0px 30px 30px 30px;box-sizing:border-box;margin-top:20px;}.Mytab_tit{color:#000;text-align:center;width:100%;line-height:80px;font-size:26px;letter-spacing:1px;font-weight:500;margin-top:80px;margin-bottom:10px;}.Mytab{width:100%;margin-bottom:30px;}.qz_info{width:100%;margin-bottom:5px;margin-top:5px;}.Mytab table{width:100%;border-collapse:collapse;border:1px solid #dfdfdf;font-size:14px;color:#333;}.center_align tbody tr td{text-align:center !important;color:#000 !important;}.mytabstyle tr td{border:1px solid #dfdfdf;height:32px;color:#666;padding:0px 0px;}`
      };
      saveTableDetail(tableContent);
      return true;
    },500)
  }
  setTimeout(() => {
    window.postMessage({
      event: 'closeTabs',
      data: ''
    }, '*');
  }, 1000);
}

const xgmPrint = async (currentZeroInfo) => {
  console.log('xgm')
  let tables = Array.from($('#zzsxgmzb > .content'));
  let declareType = "《增值税纳税申报表（小规模纳税人适用）》";
  for(let i = 0; i < tables.length; i++) {
    await asyncSetInterval(()=>{
      let titleHtml = $(tables[i]).find('.Mytab_tit').text();
      let html = $(tables[i]).prop('outerHTML');
      let tableContent = {
        declareType,
        title: titleHtml,
        html,
        css: `.content{position:relative;border:1px solid #f2f2f2;background-color:#fff;padding:0px 30px 30px 30px;box-sizing:border-box;margin-top:20px;}.Mytab_tit{color:#000;text-align:center;width:100%;line-height:80px;font-size:26px;letter-spacing:1px;font-weight:500;margin-top:80px;margin-bottom:10px;}.Mytab{width:100%;margin-bottom:30px;}.qz_info{width:100%;margin-bottom:5px;margin-top:5px;}.Mytab table{width:100%;border-collapse:collapse;border:1px solid #dfdfdf;font-size:14px;color:#333;}.center_align tbody tr td{text-align:center !important;color:#000 !important;}.mytabstyle tr td{border:1px solid #dfdfdf;height:32px;color:#666;padding:0px 0px;}`
      };
      saveTableDetail(tableContent);
      return true;
    },500)
  }
  setTimeout(() => {
    window.postMessage({
      event: 'closeTabs',
      data: ''
    }, '*');
  }, 1000);
}

function lowtag(s) {
  return s.replace(/(<\/?)([a-z\d\:]+)((\s+.+?)?>)/gi,function(s,a,b,c){return a+b.toLowerCase()+c;});
}

function deleteBox(ele) {
  ele.click();
}

export {
  autoInputAccount,
  asyncSetInterval,
  getDbList,
  zzsfpzhfwpdOption,
  zzsfpzhfwSB,
  asyncTable,
  sbbdy,
  zzsybnsrPrint,
  fsjPrint,
  qsPrint,
  xgmPrint,
  deleteBox
};
